﻿using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
using DetiInteract.DSDBroker.Parsers;
using DetiInteract.Guide.Controls.TeacherControl;
using System.Collections.Generic;
using DataVirtualization;
using System.Threading;
using System;
using System.Windows.Threading;

namespace DetiInteract.Guide.Controls.TeacherControl
{
	/// <summary>
	/// ViewModel for the Teacher Control.
	/// Control Logic is dealt with here.
	/// </summary>
	sealed class TeacherViewModel : DependencyObject
	{
		#region Dependecy Properties
		/// <summary>
		/// TeacherList Dependency property.
		/// Stores a list of teachers. Being an ObservableCollection, changes 
		/// to the collection will reflect in the UI in real time.
		/// </summary>
		public ObservableCollection<TeacherItemView> TeacherList
		{
			get { return (ObservableCollection<TeacherItemView>)GetValue(TeacherListProperty); }
			set { SetValue(TeacherListProperty, value); }
		}

		// Using a DependencyProperty as the backing store for TeacherList.  This enables animation, styling, binding, etc...
		public static readonly DependencyProperty TeacherListProperty =
			DependencyProperty.Register("TeacherList", typeof(ObservableCollection<TeacherItemView>), typeof(TeacherViewModel), new UIPropertyMetadata(null));

		#endregion

		private TeacherParser _parser = new TeacherParser();

		/// <summary>
		/// Constructor
		/// </summary>
		public TeacherViewModel()
		{
			TeacherList = new ObservableCollection<TeacherItemView>();

			//TeacherProvider teacherProvider = new TeacherProvider();
			_parser.Changed += new ProgressChangedEventHandler(Parser_Changed);
			_parser.Start();
		}

		/// <summary>
		/// Handles a Changed event from the parser.
		/// Uses the TeacherItem in the EventArgs to generate a TeacherItemView
		/// control and places it in the ObservableCollection. The Listbox on 
		/// the TeacherView will update automatically due to binding.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void Parser_Changed(object sender, ProgressChangedEventArgs e)
		{
			// Get the list of TeacherItems from the EventArgs
			List<TeacherItem> list = (List<TeacherItem>)e.UserState;

			foreach (TeacherItem ti in list)
			{
				TeacherList.Add(new TeacherItemView((TeacherItem)ti));
			}
		}
	}
}
